import { Tree, Menu, Dropdown, message } from 'antd';
import { DatabaseOutlined, DownOutlined } from '@ant-design/icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faDatabase } from '@fortawesome/free-solid-svg-icons';
import { connect } from 'react-redux';
import { useEffect } from 'react';
import request from '../../request';
import { load, updateByIndex, remove } from '../../redux/actions/main-left-tree';
import { openConnect } from '../../redux/actions/connection';
import { addTabItem } from '../../redux/actions/main';

const css = {
	lbk: { backgroundColor: '#C2D8F1' },
};

function MainLeftTree(props) {
	let item = null, expanded = [];
	useEffect(_ => request('AllConnect', { json: '' }).then(x => props.load(x.data)), []); // eslint-disable-line react-hooks/exhaustive-deps

	const onRightClick = e => item = { node: e.node.data, isLeaf: e.node.isLeaf, pid: e.node.pid };
	const onExpand = (ks, _) => expanded = ks;
	const makeNodes = ns => {
		// expanded: false    是否展开
		// loaded: false      是否 onLoadData 过
		if (ns.length > 0) {
			const ch = (pid, chs) => {
				if (chs.length > 0) return chs.map(x => ({
					title: x.name,
					isLeaf: true,
					data: x, pid,
					key: `${pid}_${x.id}`,
					icon: <FontAwesomeIcon icon={faDatabase} /> }))
					
				return []
			};

			return ns.map(x => ({
				title: x.link_name,
				key: x.id,
				expanded: expanded.indexOf(x.id),
				isLeaf: false,
				data: x,
				icon: <DatabaseOutlined />,
				children: x.children && x.children.length > 0 ?　ch(x.id, x.children) : []
			}));
		}
		return []
	};
	const onDelete = _ => {
		request('DeleteConnect', { json: item.node.id }).then(x => {
			if (x.success) {
				props.remove(item.node.id);
				message.success('删除成功！');
			}
		});
	};

	const connectMenu = <Menu>
		<Menu.Item key="1" onClick={ _ => props.openConnect(item.node) }>编辑连接</Menu.Item>
		<Menu.Item key="2" onClick={ onDelete }>删除连接</Menu.Item>
	</Menu>;
	const dbMenu = <Menu>
		<Menu.Item key="1" onClick={ _ => props.addTabItem({connectId: item.pid, db: item.node}) }>打开数据库</Menu.Item>
		<Menu.Item key="2">属性</Menu.Item>
	</Menu>;

	const menu = _ => item?.isLeaf ? dbMenu : connectMenu;

	const onLoadData = node => new Promise(y => {
		let i = props.nodes.findIndex(x => x.id === node.key);
		if (i > -1) {
			request('OpenConnect', { json: props.nodes[i].id }).then(x => {
				if (x.success) props.updateByIndex({i, children: x.data});
				y();
			});
		}
	});
	
	return <Dropdown overlay={menu} trigger={['contextMenu']}>
			<Tree
				style={css.lbk}
				showIcon
				blockNode={true}
				defaultExpandAll
				switcherIcon={<DownOutlined />}
				loadData={onLoadData}
				treeData={makeNodes(props.nodes)}
				onRightClick={onRightClick}
				onExpand={onExpand}
			/>
		</Dropdown>
}

export default connect(
	state => ({ nodes: state.mainLeftTree.nodes }),
	{ load, updateByIndex, openConnect, addTabItem, remove }
)(MainLeftTree);